package org.third.integration.ldap.ldaps;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.Certificate;
import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;

import javax.net.ssl.TrustManager;
import javax.net.ssl.TrustManagerFactory;
import javax.net.ssl.X509TrustManager;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class LdapTrustManager implements X509TrustManager {

	/** Logging support */
	private static final Logger logger = LoggerFactory.getLogger(LdapTrustManager.class);

	private X509TrustManager trustManager;

	private static final String CERTIFICATE_ALIAS = "idm_ldap";

	public LdapTrustManager(String ldapSslFile)
			throws KeyStoreException, NoSuchAlgorithmException, CertificateException, IOException {

		KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
		keyStore.load(null);
		keyStore.setCertificateEntry(CERTIFICATE_ALIAS, CertificateFactory.getInstance("X509")
				.generateCertificate(new ByteArrayInputStream(ldapSslFile.getBytes("UTF-8"))));
		TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
		tmf.init(keyStore);
		for (TrustManager tm : tmf.getTrustManagers()) {
			if (tm instanceof X509TrustManager) {
				trustManager = (X509TrustManager) tm;
				break;
			}
			if (trustManager == null) {
				throw new RuntimeException("No X509TrustManager found");
			}
		}

	}

	@Override
	public void checkClientTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
       trustManager.checkClientTrusted(x509Certificates, s);
	}

	@Override
	public void checkServerTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
		trustManager.checkClientTrusted(x509Certificates, s);
	}

	@Override
	public X509Certificate[] getAcceptedIssuers() {
        return trustManager.getAcceptedIssuers();	}

}
